import MBUtils from './mb_utils'

class MBQoS4ReciveDaemon {

    private intervalId: any = 0;
    private CHECH_INTERVAL: any = 5 * 60 * 1000;
    private MESSAGES_VALID_TIME: any = 10 * 60 * 1000;

    private recievedMessages = new Map();
    private _excuting = false;



    excute() {
        if (!this._excuting) {
            this._excuting = true;


            var arr = Array.from(this.recievedMessages.keys());
            for (var i = 0; i < arr.length; i++) {
                var key = arr[i];
                var recievedTime = this.recievedMessages.get(key);
                var delta = MBUtils.getCurrentUTCTimestamp() - (recievedTime ? recievedTime : 0);
                if (delta >= this.MESSAGES_VALID_TIME) {
                    this.recievedMessages.delete(key);
                }
            }
        }
        this._excuting = false;
    };

    startup(immediately: any) {
        this.stop();
        if (this.recievedMessages != null && this.recievedMessages.size > 0) {
            var arr = Array.from(this.recievedMessages.keys());
            for (var i = 0; i < arr.length; i++) {
                var key = arr[i];
                this.putImpl(key);
            }
        }
        if (immediately) {
            this.excute();
        }
        let that = this;
        this.intervalId = setInterval(function () {
            that.excute();
        }, this.CHECH_INTERVAL);
    };

    stop() {
        if (this.intervalId && this.intervalId !== 0)
            clearInterval(this.intervalId);
    };

    addRecievedProtocal(p: any) {
        if (p && p.QoS)
            this.addRecieved(p.fp);
    };

    addRecieved(fingerPrintOfProtocal: any) {
        if (fingerPrintOfProtocal) {
            this.putImpl(fingerPrintOfProtocal);
        }
    };

    putImpl(fingerPrintOfProtocal: any) {
        if (fingerPrintOfProtocal)
            this.recievedMessages.set(fingerPrintOfProtocal, MBUtils.getCurrentUTCTimestamp());
    };

    hasRecieved(fingerPrintOfProtocal: any) {
        return this.recievedMessages.has(fingerPrintOfProtocal);
    };


    clear() {
        this.recievedMessages.clear();
    };

    size() {
        return this.recievedMessages.size;
    };

    setCheckInterval(interval: any) {
        this.CHECH_INTERVAL = interval;
    };

    setMessageValidTime(time: any) {
        this.MESSAGES_VALID_TIME = time;
    };


}

export default new MBQoS4ReciveDaemon();